#!/usr/bin/env python

"""\
Set copyright end year across the distribution.
"""

import sys
import os
import re
import argparse
import datetime


THIS_YEAR = datetime.date.today().year
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
PATTERN = re.compile(br"(?<=opyright 2009-)\d+")


def find_files(root_dir):
    for d, subdirs, fnames in os.walk(root_dir, topdown=True):
        for fn in fnames:
            yield os.path.join(d, fn)
        subdirs[:] = [_ for _ in subdirs if _ != ".git"]


def bump_end_year(root_dir, year):
    year = "%d" % year
    for fn in find_files(root_dir):
        if fn == os.path.abspath(__file__):
            continue
        print("processing %r" % (fn,))
        with open(fn, "rb") as f:
            content = f.read()
        with open(fn, "wb") as f:
            f.write(re.sub(PATTERN, year, content))


def make_parser():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-y", type=int, metavar="YYYY", default=THIS_YEAR,
                        help="copyright end year (default = current)")
    return parser


def main(argv):
    parser = make_parser()
    args = parser.parse_args(argv[1:])
    repo_root = os.path.dirname(THIS_DIR)
    bump_end_year(repo_root, args.y)


if __name__ == "__main__":
    main(sys.argv)
